package com.xnx3.autoPublish.model;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

import com.xnx3.BaseVO;

/**
 * http请求健康监测
 * @author 管雷鸣
 *
 */
public class HttpRequestJiankangjiance {
	
	public static BaseVO request(String url) {
		BaseVO vo = new BaseVO();
		
        try {
        	String message="";
            URL urlURL =new URL(url);
            HttpURLConnection connection= (HttpURLConnection) urlURL.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5*1000);
            connection.connect();
//            InputStream inputStream=connection.getInputStream();
            InputStream inputStream = null;
        	try {
        		inputStream = connection.getInputStream();
        	} catch (IOException ioe) {
        	    if (connection instanceof HttpURLConnection) {
        	        HttpURLConnection httpConn = (HttpURLConnection) connection;
        	        int statusCode = httpConn.getResponseCode();
        	        if (statusCode != 200) {
        	        	inputStream = httpConn.getErrorStream();
        	        	vo.setResult(BaseVO.FAILURE);
        	        }else {
        	        	vo.setResult(BaseVO.SUCCESS);
        	        }
        	    }
        	}
            
            byte[] data=new byte[1024];
            StringBuffer sb=new StringBuffer();
            int length=0;
            while ((length=inputStream.read(data))!=-1){
                String s=new String(data, Charset.forName("utf-8"));
                sb.append(s);
            }
            message=sb.toString();
            inputStream.close();
            connection.disconnect();
            vo.setInfo(message);
            return vo;
        } catch (java.net.SocketTimeoutException eimeoutE) {
//        	eimeoutE.printStackTrace();
        	System.out.println(eimeoutE.getMessage());
        	return BaseVO.failure(eimeoutE.getMessage());
        } catch (Exception e) {
//            e.printStackTrace();
            return BaseVO.failure(e.getMessage());
        }
        
	}
	
	public static void main(String[] args) {
		BaseVO requestVO = request("http://123.45.23.2");
		System.out.println(requestVO);
	}
}
